﻿using System.Drawing;
using System.Collections;

namespace TestAnimation
{
    class Explosion
    {
        int size;
        readonly Vector position;
        private readonly ArrayList Segments;
        const int speed=3;

        public struct Segment
        {
            internal Vector point1, point2, velocity;
        }
        public struct Line
        {
            internal Vector point1, point2;
            internal Pen pen;
        }
        public struct Circle
        {
            internal Vector point1;
            internal int size;
            internal Pen pen;
        }

        public Explosion(ScreenObject obj)
        {
            position = obj.Position;
            Segments = new ArrayList(obj.TransformedPoints.Count);


            for (int i = 0; i < obj.TransformedPoints.Count - 1; i++)
            {
                NewSegment((Point)(obj.TransformedPoints[i]), (Point)(obj.TransformedPoints[i + 1]));
            }
            NewSegment((Point)(obj.TransformedPoints[0]), (Point)(obj.TransformedPoints[obj.TransformedPoints.Count - 1]));

        }
        void NewSegment(Point p1, Point p2)
            {
                var s = new Segment { point1 = new Vector(), point2 = new Vector(), velocity = new Vector() };
                s.point1.X = p1.X;
                s.point1.Y = p1.Y;

                s.point2.X = p2.X;
                s.point2.Y = p2.Y;
                s.point1 -= position;
                s.point2 -= position;
                s.velocity = (s.point1 + s.point2) * .5f;
                s.velocity = s.velocity.Normalize() * speed;
                Segments.Add(s);
            }

        public bool Draw(Screen screen)
        {
            var pen = new Pen(Color.FromArgb(255 - size * 255 / Globals.explosionMaxSize, (255 - size * 255 / Globals.explosionMaxSize) / 3, 0));
            var circle = new Circle {pen = pen, point1 = position, size = size};
            screen.Add(circle);      

            var light = (byte)(255 - size * 255 / Globals.explosionMaxSize);
            pen = new Pen(Color.FromArgb(light, light, light));

            // Vectors explosion
            foreach (Segment s in Segments)
            {
                var p1 = new Vector();
                var p2 = new Vector();
                p1.X = (int)(s.point1.X + s.velocity.X * size * 3 + position.X);
                p1.Y = (int)(s.point1.Y + s.velocity.Y * size * 3 + position.Y);
                p2.X = (int)(s.point2.X + s.velocity.X * size * 3 + position.X);
                p2.Y = (int)(s.point2.Y + s.velocity.Y * size * 3 + position.Y);

                var line = new Line {point1 = p1, point2 = p2, pen = pen};
                screen.Add(line);
            }

            size += speed;
            return size > Globals.explosionMaxSize;
        }
    }
}
